package wcu;

import java.io.*;
import java.net.*;

public class Network {

	private static Network network = null;
	private InetAddress addr;
	private int port;
	private Socket sock;
	private MettlerScaleCommands mSC;
	
	private Network() {
		this.mSC = new MettlerScaleCommands();
	}

	public static Network getInstance() {
		if (network == null) {
			network = new Network();
		}
		return network;
	}

	public void close() throws IOException {
		sock.close();
	}

	public void connectToServer(String ip, int port) throws IOException {
		this.addr = InetAddress.getByName(ip);
		this.port = port;
		sock = new Socket(this.addr, this.port);
		mSC.setSocket(sock);
	}

	public void sendToServer(String message) throws UnknownHostException {
		if (sock == null)
			return;
		try {
			OutputStream oS = sock.getOutputStream();
			BufferedOutputStream bOS = new BufferedOutputStream(oS);
			DataOutputStream dOS = new DataOutputStream(bOS);
			
			dOS.writeBytes(message + "\r\n");
			dOS.flush();
			
		} catch (IOException e) {
			e.printStackTrace();
		}
	}

	public String readFromServer() throws UnknownHostException {
		if (sock == null)
			return "NO CONNECTION";

		try {
			InputStream iS = sock.getInputStream();
			InputStreamReader iSR = new InputStreamReader(iS);
			BufferedReader bR = new BufferedReader(iSR);

			String sentenceFromServer = bR.readLine();

			return sentenceFromServer;

		} catch (IOException e) {
			e.printStackTrace();
		}

		return "";
	}
	
	public MettlerScaleCommands getMettlerScaleCommands(){
		return this.mSC;
	}
	
	public String waitForResponse(){
		try {
			InputStream response = sock.getInputStream();
			
	        byte[] buffer = new byte[4096];
	        response.read(buffer);
	        
	        response.close();
	        return new String(buffer);

	 
		} catch (IOException e) {
			e.printStackTrace();
		}
		return null;
	}
}
